import axios from "axios";
import { getStorage, removeStorage } from "@/utils/storage";
import { appid, domainUrl } from "@/utils/appInfo";
import { showFailToast } from "vant";

const getQueryParams = () => {
  const queryString = window.location.search; // 获取查询字符串，例如 '?id=123&name=abc'
  const urlParams = new URLSearchParams(queryString);

  const params = {};
  urlParams.forEach((value, key) => {
    if (key != "code" && key != "state") {
      params[key] = value; // 将参数存入对象
    }
  });

  return params;
};

// 创建axios实例
const service = axios.create({
  baseURL: "", // api的base_url
  timeout: 5000, // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 可以在这里添加请求头等信息
    // if (store.getters.token) {
    //   config.headers['X-Token'] = getToken();
    // }
    const token = getStorage("token");
    if (token) {
      config.headers["Authorization"] = "JWT " + token;
    }
    return config;
  },
  (error) => {
    // 请求错误处理
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    console.log(
      "%c [ response ]-38",
      "font-size:13px; background:#3def69; color:#81ffad;",
      response
    );
    // 对响应数据做处理，例如只返回data部分
    const res = response.data;
    if (res.code == 40100) {
      removeStorage("token");
      const redirectUrl = new URL(domainUrl);
      const queryParams = getQueryParams();
      console.log(
        "%c [ queryParams ]-58",
        "font-size:13px; background:#b9a902; color:#fded46;",
        queryParams
      );
      Object.entries(queryParams).forEach(([key, value]) => {
        redirectUrl.searchParams.append(key, value);
      });
      const fullUrl = redirectUrl.toString();
      let url = encodeURIComponent(fullUrl);
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`;
    } else if (res.code != 20000) {
      showFailToast({ message: "失败:" + res.message, duration: 5000 });
      return;
    }
    // if (res.code !== 200) {
    //   Message({
    //     message: res.message,
    //     type: 'error',
    //     duration: 5 * 1000
    //   });
    //   // 50001: 非法的token; 50002: 其他客户端错误; 50003: 认证失败; 50004: 授权失败; 50005: 未找到用户
    //   if (res.code === 50001 || res.code === 50002 || res.code === 50003 || res.code === 50004 || res.code === 50005) {
    //     // 移除token
    //     resetToken();
    //     // 跳转到登录页面
    //     location.reload();
    //   }
    //   return Promise.reject('error');
    // } else {
    //   return res;
    // }
    return response;
  },
  (error) => {
    console.log(
      "%c [ error ]-78",
      "font-size:13px; background:#fde59c; color:#ffffe0;",
      error
    );
    if (error.status == "401") {
      removeStorage("token");
      const redirectUrl = new URL(domainUrl);
      const queryParams = getQueryParams();
      console.log(
        "%c [ queryParams ]-102",
        "font-size:13px; background:#e9a46b; color:#ffe8af;",
        queryParams
      );
      Object.entries(queryParams).forEach(([key, value]) => {
        url.searchParams.append(key, value);
      });
      const fullUrl = redirectUrl.toString();
      let url = encodeURIComponent(fullUrl);
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`;
    }
    console.log("err" + error); // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // });
    return Promise.reject(error);
  }
);

export default service;
